import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
import { message } from 'antd';

// 请求缓存
const requestCache = new Map<string, { data: any; timestamp: number; ttl: number }>();
const CACHE_TTL = 5 * 60 * 1000; // 5分钟缓存

// 防抖函数
const debounceMap = new Map<string, NodeJS.Timeout>();

function debounce<T extends (...args: any[]) => any>(
  key: string,
  func: T,
  delay: number = 300
): (...args: Parameters<T>) => Promise<ReturnType<T>> {
  return (...args: Parameters<T>): Promise<ReturnType<T>> => {
    return new Promise((resolve, reject) => {
      // 清除之前的定时器
      if (debounceMap.has(key)) {
        clearTimeout(debounceMap.get(key)!);
      }

      // 设置新的定时器
      const timeoutId = setTimeout(async () => {
        try {
          const result = await func(...args);
          resolve(result);
        } catch (error) {
          reject(error);
        } finally {
          debounceMap.delete(key);
        }
      }, delay);

      debounceMap.set(key, timeoutId);
    });
  };
}

// 缓存工具函数
function getCacheKey(url: string, params?: any): string {
  return `${url}${params ? JSON.stringify(params) : ''}`;
}

function getFromCache(key: string): any | null {
  const cached = requestCache.get(key);
  if (cached && Date.now() - cached.timestamp < cached.ttl) {
    return cached.data;
  }
  if (cached) {
    requestCache.delete(key);
  }
  return null;
}

function setCache(key: string, data: any, ttl: number = CACHE_TTL): void {
  requestCache.set(key, {
    data,
    timestamp: Date.now(),
    ttl
  });
}

// API基础配置
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:3002/api';

// 调试信息（仅开发环境）
if (import.meta.env.DEV) {
  console.log('API Base URL:', API_BASE_URL);
  console.log('Environment variables:', {
    VITE_API_BASE_URL: import.meta.env.VITE_API_BASE_URL,
    NODE_ENV: import.meta.env.NODE_ENV,
    MODE: import.meta.env.MODE
  });
}

// 创建axios实例
const apiClient: AxiosInstance = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器
apiClient.interceptors.request.use(
  (config: any) => {
    // 仅在开发环境且启用详细日志时输出
    if (import.meta.env.DEV && import.meta.env.VITE_ENABLE_API_LOGS === 'true') {
      console.log('🔗 API Request:', config.method?.toUpperCase(), config.url);
      if (config.data) {
        console.log('📤 Request data:', config.data);
      }
    }

    // 添加认证token
    const token = localStorage.getItem('admin_token');
    if (token && config.headers) {
      config.headers.Authorization = `Bearer ${token}`;
    }

    // 对于GET请求，检查缓存
    if (config.method === 'get' && !config.skipCache) {
      const cacheKey = getCacheKey(config.url, config.params);
      const cachedData = getFromCache(cacheKey);
      if (cachedData) {
        // 返回缓存的数据
        return Promise.reject({
          __cached: true,
          data: cachedData
        });
      }
    }

    // 添加时间戳防止浏览器缓存（但不影响我们的应用缓存）
    if (config.method === 'get' && !config.skipTimestamp) {
      config.params = {
        ...config.params,
        _t: Date.now(),
      };
    }

    return config;
  },
  (error) => {
    // 处理缓存数据
    if (error.__cached) {
      return Promise.resolve(error.data);
    }

    if (import.meta.env.DEV) {
      console.error('Request interceptor error:', error);
    }
    return Promise.reject(error);
  }
);

// 响应拦截器
apiClient.interceptors.response.use(
  (response: AxiosResponse) => {
    // 统一处理响应数据
    const { data, config } = response;

    // 对于GET请求，缓存响应数据
    if (config.method === 'get' && !config.skipCache) {
      const cacheKey = getCacheKey(config.url, config.params);
      setCache(cacheKey, data);
    }

    // 如果后端返回的是包装格式
    if (data && typeof data === 'object' && 'success' in data) {
      if (data.success) {
        // 返回完整的响应数据，包括data、pagination、total等
        return data;
      } else {
        message.error(data.message || '请求失败');
        return Promise.reject(new Error(data.message || '请求失败'));
      }
    }

    return data;
  },
  (error) => {
    console.error('Response interceptor error:', error);
    console.error('Error details:', {
      message: error.message,
      code: error.code,
      config: error.config,
      response: error.response
    });

    // 处理HTTP错误状态码
    if (error.response) {
      const { status, data } = error.response;

      switch (status) {
        case 401:
          message.error('未授权，请重新登录');
          localStorage.removeItem('admin_token');
          localStorage.removeItem('admin_user');
          window.location.href = '/login';
          break;
        case 403:
          message.error('权限不足');
          break;
        case 404:
          // 不在这里显示404错误，让组件处理
          break;
        case 500:
          message.error('服务器内部错误');
          break;
        default:
          // 对于400等业务错误，不在这里显示，让组件处理
          if (status >= 500) {
            message.error(data?.message || `服务器错误 (${status})`);
          }
      }
    } else if (error.request) {
      message.error('网络连接失败，请检查网络');
    } else {
      message.error(error.message || '请求失败');
    }

    return Promise.reject(error);
  }
);

// API服务类
export class ApiService {
  // GET请求
  static async get<T = any>(url: string, params?: any): Promise<T> {
    const response = await apiClient.get(url, { params });
    return response;
  }

  // POST请求
  static async post<T = any>(url: string, data?: any): Promise<T> {
    const response = await apiClient.post(url, data);
    return response;
  }

  // PUT请求
  static async put<T = any>(url: string, data?: any): Promise<T> {
    const response = await apiClient.put(url, data);
    return response;
  }

  // PATCH请求
  static async patch<T = any>(url: string, data?: any): Promise<T> {
    const response = await apiClient.patch(url, data);
    return response;
  }

  // DELETE请求
  static async delete<T = any>(url: string): Promise<T> {
    const response = await apiClient.delete(url);
    return response;
  }

  // 文件上传
  static async upload<T = any>(url: string, file: File, onProgress?: (progress: number) => void): Promise<T> {
    const formData = new FormData();
    formData.append('file', file);

    const response = await apiClient.post(url, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
      onUploadProgress: (progressEvent) => {
        if (onProgress && progressEvent.total) {
          const progress = Math.round((progressEvent.loaded * 100) / progressEvent.total);
          onProgress(progress);
        }
      },
    });

    return response;
  }

  // 批量上传
  static async uploadMultiple<T = any>(
    url: string,
    files: File[],
    onProgress?: (progress: number) => void
  ): Promise<T> {
    const formData = new FormData();
    files.forEach((file, index) => {
      formData.append(`files`, file);
    });

    const response = await apiClient.post(url, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
      onUploadProgress: (progressEvent) => {
        if (onProgress && progressEvent.total) {
          const progress = Math.round((progressEvent.loaded * 100) / progressEvent.total);
          onProgress(progress);
        }
      },
    });

    return response;
  }

  // 下载文件
  static async download(url: string, filename?: string): Promise<void> {
    const response = await apiClient.get(url, {
      responseType: 'blob',
    });

    // 创建下载链接
    const blob = new Blob([response]);
    const downloadUrl = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = downloadUrl;
    link.download = filename || 'download';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(downloadUrl);
  }

  // 健康检查
  static async healthCheck(): Promise<boolean> {
    try {
      await apiClient.get('/health');
      return true;
    } catch (error) {
      return false;
    }
  }

  // 设置认证token
  static setAuthToken(token: string): void {
    localStorage.setItem('admin_token', token);
  }

  // 清除认证token
  static clearAuthToken(): void {
    localStorage.removeItem('admin_token');
    localStorage.removeItem('admin_user');
  }

  // 获取认证token
  static getAuthToken(): string | null {
    return localStorage.getItem('admin_token');
  }

  // 检查是否已认证
  static isAuthenticated(): boolean {
    const token = this.getAuthToken();
    return !!token;
  }
}

// 产品API服务
export const productApi = {
  // 获取产品列表
  getProducts: (params?: any) => ApiService.get('/admin/products', params),

  // 获取产品详情
  getProduct: (id: string) => ApiService.get(`/admin/products/${id}`),

  // 创建产品
  createProduct: (data: any) => ApiService.post('/admin/products', data),

  // 更新产品
  updateProduct: (id: string, data: any) => ApiService.put(`/admin/products/${id}`, data),

  // 删除产品
  deleteProduct: (id: string) => ApiService.delete(`/admin/products/${id}`),

  // 批量删除产品
  batchDeleteProducts: (ids: string[]) => ApiService.post('/admin/products/batch-delete', { ids }),

  // 更新产品状态
  updateProductStatus: (id: string, status: string) => ApiService.patch(`/admin/products/${id}/status`, { status }),

  // 批量更新产品状态
  batchUpdateProductStatus: (ids: string[], status: string) => ApiService.post('/admin/products/batch-status', { ids, status }),

  // 获取产品统计
  getProductStats: () => ApiService.get('/admin/products/stats'),

  // 搜索产品
  searchProducts: (query: string, params?: any) => ApiService.get('/admin/products/search', { q: query, ...params }),
};

// 用户API服务
export const userApi = {
  // 获取用户列表
  getUsers: (params?: any) => ApiService.get('/admin/users', params),

  // 获取用户详情
  getUser: (id: string) => ApiService.get(`/admin/users/${id}`),

  // 更新用户状态
  updateUserStatus: (id: string, status: string) => ApiService.patch(`/admin/users/${id}/status`, { status }),

  // 获取用户统计
  getUserStats: () => ApiService.get('/admin/users/stats'),
};

// 订单API服务
export const orderApi = {
  // 获取订单列表
  getOrders: (params?: any) => ApiService.get('/admin/orders', params),

  // 获取订单详情
  getOrder: (id: string) => ApiService.get(`/admin/orders/${id}`),

  // 更新订单状态
  updateOrderStatus: (id: string, status: string) => ApiService.patch(`/admin/orders/${id}/status`, { status }),

  // 获取订单统计
  getOrderStats: () => ApiService.get('/admin/orders/stats'),
};

// 分类API服务
export const categoryApi = {
  // 获取分类列表
  getCategories: (params?: any) => ApiService.get('/admin/categories', params),

  // 获取分类详情
  getCategory: (id: string) => ApiService.get(`/admin/categories/${id}`),

  // 创建分类
  createCategory: (data: any) => ApiService.post('/admin/categories', data),

  // 更新分类
  updateCategory: (id: string, data: any) => ApiService.put(`/admin/categories/${id}`, data),

  // 删除分类
  deleteCategory: (id: string) => ApiService.delete(`/admin/categories/${id}`),
};

// 店铺API服务
export const shopApi = {
  // 获取店铺列表
  getShops: (params?: any) => ApiService.get('/admin/shops', params),

  // 获取店铺详情
  getShop: (id: string) => ApiService.get(`/admin/shops/${id}`),

  // 更新店铺状态
  updateShopStatus: (id: string, status: string) => ApiService.patch(`/admin/shops/${id}/status`, { status }),

  // 获取店铺统计
  getShopStats: () => ApiService.get('/admin/shops/stats'),
};

// 导出axios实例（用于特殊情况）
export { apiClient };

// 导出默认API服务
export default ApiService;
